<template>
  <div class="dashboard-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span style="font-size: 50px;padding-bottom: 20px">商家工作台</span>
      </div>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-card class="order-card">
            <div class="order-title">商家订单</div>
            <div class="order-count">{{ orderCount}}</div>
            <el-button type="primary" @click="handleViewOrders">查看订单</el-button>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="sales-card">
            <div class="sales-title">总销售额</div>
            <div class="sales-count">{{ totalRevenue }}</div>
            <el-button type="success" @click="handleViewSales">查看详情</el-button>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="menu-card">
            <div class="menu-title">菜单管理</div>
            <div class="menu-count">{{ dishCount }}</div>
            <el-button type="warning" @click="handleViewMenu">管理菜单</el-button>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
  <div>
<!--    <h1>商家来单提醒</h1>-->
    <div v-if="isConnected">
<!--      <p>WebSocket 已连接。</p>-->
      <!-- 消息显示区域 -->
      <div id="messageArea" style="display:none;">
        <div v-for="message in messages" :key="message.id">
          <p>{{ message.content }}</p>
        </div>
      </div>
      <!-- 隐藏的音频元素用于播放声音 -->
      <audio ref="audioPlayer" style="display:none;">
        <source src="../../../assets/preview.mp3" type="audio/mpeg">
      </audio>
    </div>
<!--    <div v-else>
      <button @click="initWebSocket">连接WebSocket</button>
    </div>-->
  </div>
</template>

<script>
import { ref,onMounted } from 'vue';
import { ElMessage, ElCard, ElRow, ElCol, ElButton,ElNotification } from 'element-plus';
import { useRouter } from 'vue-router';
import axios from "axios";

export default {
  // 组件的选项
  setup() {
    const router = useRouter(); // 创建路由对象实例

    // 组件的逻辑
    const orderCount = ref(0);
    const salesAmount = ref(0);
    const menuCount = ref(0);
    const totalRevenue = ref(0);
    const dishCount = ref(0);  // 新增：用于存储菜品数量

    //来单提醒
    const messages = ref([]);
    const isConnected = ref(false);
    let websocket = null;
    const audioPlayer = ref(null); // 引用 audio 元素

    // 获取当前日期
    const today = new Date();
    const formattedToday = today.toISOString().split('T')[0];

    const fetchOrderCount = async () => {
      try {
        // 从 sessionStorage 获取 loginUser 的 mid 和 mallid
        const loginUser = JSON.parse(sessionStorage.getItem('loginUser'));
        const mallid = loginUser.mid;

        const response = await axios.get(`http://localhost:8085/indent/count/date?date=${formattedToday}&mallid=${mallid}`);
        orderCount.value = response.data;
      } catch (error) {
        console.error('获取订单数量失败:', error);
      }
    };

    const fetchTotalRevenue = async () => {
      try {
        const loginUser = JSON.parse(sessionStorage.getItem('loginUser'));
        const mallid = loginUser.mid;
        const response = await axios.get(`http://localhost:8085/indent/sum/totalprice?mallid=${mallid}`);
        totalRevenue.value = response.data;
      } catch (error) {
        console.error('获取商家营业额失败:', error);
      }
    };

    const fetchDishCount = async () => {  // 新增：获取菜品数量的函数
      try {
        const loginUser = JSON.parse(sessionStorage.getItem('loginUser'));
        const mallid = loginUser.mid;
        const response = await axios.get(`http://localhost:8085/dishes/count/dishes?mallid=${mallid}`);
        dishCount.value = response.data;  // 将获取到的菜品数量赋值给 dishCount
      } catch (error) {
        console.error('获取菜品数量失败:', error);
      }
    };

    const handleViewOrders = () => {
      // ElMessage.success('点击查看今日订单');
      router.push('/home/mall/order');
    };

    const handleViewSales = () => {
      // ElMessage.success('点击查看今日销售额');
      router.push('/home/mall/order');
    };

    const handleViewMenu = () => {
      router.push('/home/mall/canmall');
    };

    // 来单提醒相关的函数
    const initWebSocket = () => {
      const socketUrl = 'ws://127.0.0.1:8085/ws/indentid';
      websocket = new WebSocket(socketUrl);

      websocket.onopen = () => {
        isConnected.value = true;
        console.log('WebSocket 连接成功');
      };

      websocket.onmessage = (event) => {
        const message = JSON.parse(event.data);
        messages.value.push(message);
        console.log(message);
        playAudio();//播放音频
        showNotification(message);
      };

      websocket.onerror = (error) => {
        console.error('WebSocket 出现错误:', error);
      };

      websocket.onclose = () => {
        isConnected.value = false;
        console.log('WebSocket 连接已关闭');
      };
    };

    const playAudio = () => {
      const player = audioPlayer.value;
      if (player) {
        player.currentTime = 0;
        console.log('尝试播放音频...');
        player.play()
            .then(() => {
              console.log('音频播放成功');
            })
            .catch((error) => {
              console.error('音频播放失败:', error);
            });
      }
    };

    const showNotification = (message) => {
      ElNotification({
        title: '新订单提醒',
        message: `订单号：${message.OrderId}`,
        type:'success',
        duration: 0,
        dangerouslyUseHTMLString: true,
      });
    };

    onMounted(() => {
      fetchOrderCount();
      fetchTotalRevenue();
      fetchDishCount();  // 在挂载时调用获取菜品数量的函数
      initWebSocket();
    });

    // 返回对象，包含响应式数据和方法
    return {
      orderCount,
      salesAmount,
      menuCount,
      totalRevenue,
      dishCount,  // 将 dishCount 暴露给模板
      handleViewOrders,
      handleViewSales,
      handleViewMenu,
      messages,
      isConnected,
      audioPlayer,
    };
  },
};
</script>

<style>
.dashboard-container {
  margin: 30px;
  font-size: 14px;
}

.box-card {
  width: 100%;
}

.order-card,
.sales-card,
.menu-card {
  text-align: center;
  margin-bottom: 20px;
}

.order-title,
.sales-title,
.menu-title {
  font-size: 24px;
  margin-bottom: 20px;
}

.order-count,
.sales-count,
.menu-count {
  font-size: 48px;
  font-weight: bold;
  margin-bottom: 20px;
}
</style>